import os
import sys
import tempfile
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QRadioButton, QButtonGroup, QPushButton, QFileDialog, QMessageBox,
    QGroupBox, QLineEdit, QProgressBar, QTextEdit, QDialog, QScrollArea
)
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QLinearGradient, QColor, QFont, QPalette
from PyQt5.QtCore import Qt, QRect, QSize
from PyPDF2 import PdfReader, PdfWriter
from docx import Document
import comtypes.client  # 改回使用comtypes

class FileMergerApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文档合并工具")
        self.setGeometry(100, 100, 800, 650)
        
        # 设置应用图标
        self.setWindowIcon(QIcon(self.get_app_icon()))
        
        # 检查并显示首次运行声明
        self.check_first_run()
        
        # 初始化变量
        self.file_type = "pdf"  # 默认PDF
        self.merge_type = "alternating"  # 默认奇偶页交替合并
        self.first_file = ""
        self.second_file = ""
        self.reverse_option = "none"  # 默认不逆序
        self.output_dir = os.getcwd()  # 默认输出目录
        self.output_file = ""
        
        # 创建主部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QVBoxLayout(central_widget)
        self.layout.setSpacing(16)  # 整体行距16px
        self.layout.setContentsMargins(15, 15, 15, 15)
        
        # 添加标题
        title_layout = QHBoxLayout()
        title_icon = QLabel()
        title_icon.setPixmap(QPixmap(self.get_app_icon()).scaled(40, 40, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        title_layout.addWidget(title_icon)
        
        title_label = QLabel("文档合并工具")
        self.setFont(title_label, 18, QFont.Bold)
        title_label.setStyleSheet("color: #2B2D42;")
        title_layout.addWidget(title_label, 1)
        title_layout.addStretch()
        
        # 添加帮助按钮
        self.help_btn = QPushButton("使用说明")
        self.help_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF"))
        self.help_btn.setFixedWidth(100)
        self.help_btn.setFont(QFont("微软雅黑", 11))
        self.help_btn.clicked.connect(self.show_help)
        title_layout.addWidget(self.help_btn)
        
        self.layout.addLayout(title_layout)
        
        # 步骤1: 选择文档格式
        file_type_box = QGroupBox("步骤1: 选择文档格式")
        file_type_box.setStyleSheet(self.get_groupbox_style())
        file_type_layout = QHBoxLayout(file_type_box)
        
        self.file_type_group = QButtonGroup(self)
        self.pdf_radio = QRadioButton("PDF文档")
        self.pdf_radio.setChecked(True)
        self.pdf_radio.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.word_radio = QRadioButton("Word文档")
        self.word_radio.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.mixed_radio = QRadioButton("混合模式")
        self.mixed_radio.setStyleSheet("font-size: 16px; color: #2B2D42;")
        
        self.file_type_group.addButton(self.pdf_radio, 1)
        self.file_type_group.addButton(self.word_radio, 2)
        self.file_type_group.addButton(self.mixed_radio, 3)
        
        file_type_layout.addWidget(self.pdf_radio)
        file_type_layout.addWidget(self.word_radio)
        file_type_layout.addWidget(self.mixed_radio)
        file_type_layout.addStretch()
        self.layout.addWidget(file_type_box)
        
        # 步骤2: 选择合并方式
        merge_type_box = QGroupBox("步骤2: 选择合并方式")
        merge_type_box.setStyleSheet(self.get_groupbox_style())
        merge_type_layout = QVBoxLayout(merge_type_box)
        
        self.merge_type_group = QButtonGroup(self)
        self.direct_radio = QRadioButton("直接合并（首文件 + 尾文件）")
        self.direct_radio.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.alternating_radio = QRadioButton("奇偶页交替合并（扫描文件专用）")
        self.alternating_radio.setChecked(True)
        self.alternating_radio.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.merge_type_group.addButton(self.direct_radio, 1)
        self.merge_type_group.addButton(self.alternating_radio, 2)
        
        merge_type_layout.addWidget(self.direct_radio)
        merge_type_layout.addWidget(self.alternating_radio)
        self.layout.addWidget(merge_type_box)
        
        # 步骤3: 逆序选项
        reverse_box = QGroupBox("步骤3: 逆序选项")
        reverse_box.setStyleSheet(self.get_groupbox_style())
        reverse_layout = QVBoxLayout(reverse_box)
        
        self.reverse_group = QButtonGroup(self)
        self.reverse_none = QRadioButton("不需要逆序")
        self.reverse_none.setChecked(True)
        self.reverse_none.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.reverse_odd = QRadioButton("逆序奇数页文件")
        self.reverse_odd.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.reverse_even = QRadioButton("逆序偶数页文件")
        self.reverse_even.setStyleSheet("font-size: 16px; color: #2B2D42;")
        self.reverse_both = QRadioButton("两者都逆序")
        self.reverse_both.setStyleSheet("font-size: 16px; color: #2B2D42;")
        
        self.reverse_group.addButton(self.reverse_none, 1)
        self.reverse_group.addButton(self.reverse_odd, 2)
        self.reverse_group.addButton(self.reverse_even, 3)
        self.reverse_group.addButton(self.reverse_both, 4)
        
        reverse_layout.addWidget(self.reverse_none)
        reverse_layout.addWidget(self.reverse_odd)
        reverse_layout.addWidget(self.reverse_even)
        reverse_layout.addWidget(self.reverse_both)
        self.layout.addWidget(reverse_box)
        
        # 文件选择区域
        files_box = QGroupBox("步骤4: 选择文件")
        files_box.setStyleSheet(self.get_groupbox_style())
        files_layout = QVBoxLayout(files_box)
        
        # 第一个文件
        file1_layout = QHBoxLayout()
        file1_layout.setSpacing(8)  # 标签-输入框间距8px
        file1_label = QLabel("第一个文件:")
        self.setFont(file1_label, 10)
        file1_label.setStyleSheet("color: #2B2D42; font-weight: bold; min-width: 100px;")  # 确保足够宽度
        file1_layout.addWidget(file1_label)
        
        self.file1_edit = QLineEdit()
        self.file1_edit.setStyleSheet("""
            QLineEdit {
                background-color: #FFFFFF;
                border: 1px solid #CED4DA;
                border-radius: 5px;
                padding: 6px;
                font-size: 13px;
                color: #495057;
            }
            QLineEdit::placeholder {
                color: #6C757D;
            }
        """)
        self.setFont(self.file1_edit, 13)
        file1_layout.addWidget(self.file1_edit, 1)
        
        self.browse_file1_btn = QPushButton("浏览...")
        self.browse_file1_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF"))
        self.browse_file1_btn.setFixedWidth(100)
        self.setFont(self.browse_file1_btn, 12, QFont.Medium)
        self.browse_file1_btn.clicked.connect(lambda: self.select_file("file1"))
        file1_layout.addWidget(self.browse_file1_btn)
        
        files_layout.addLayout(file1_layout)
        
        # 第二个文件
        file2_layout = QHBoxLayout()
        file2_layout.setSpacing(8)  # 标签-输入框间距8px
        file2_label = QLabel("第二个文件:")
        self.setFont(file2_label, 10)
        file2_label.setStyleSheet("color: #2B2D42; font-weight: bold; min-width: 100px;")  # 确保足够宽度
        file2_layout.addWidget(file2_label)
        
        self.file2_edit = QLineEdit()
        self.file2_edit.setStyleSheet("""
            QLineEdit {
                background-color: #FFFFFF;
                border: 1px solid #CED4DA;
                border-radius: 5px;
                padding: 6px;
                font-size: 13px;
                color: #495057;
            }
            QLineEdit::placeholder {
                color: #6C757D;
            }
        """)
        self.setFont(self.file2_edit, 13)
        file2_layout.addWidget(self.file2_edit, 1)
        
        self.browse_file2_btn = QPushButton("浏览...")
        self.browse_file2_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF"))
        self.browse_file2_btn.setFixedWidth(100)
        self.setFont(self.browse_file2_btn, 12, QFont.Medium)
        self.browse_file2_btn.clicked.connect(lambda: self.select_file("file2"))
        file2_layout.addWidget(self.browse_file2_btn)
        
        files_layout.addLayout(file2_layout)
        self.layout.addWidget(files_box)
        
        # 输出设置
        output_box = QGroupBox("步骤5: 输出设置")
        output_box.setStyleSheet(self.get_groupbox_style())
        output_layout = QVBoxLayout(output_box)
        
        # 输出目录选择
        dir_layout = QHBoxLayout()
        dir_layout.setSpacing(8)  # 标签-输入框间距8px
        dir_label = QLabel("输出目录:")
        self.setFont(dir_label, 10)
        dir_label.setStyleSheet("color: #2B2D42; font-weight: bold; min-width: 100px;")  # 确保足够宽度
        dir_layout.addWidget(dir_label)
        
        self.dir_edit = QLineEdit(self.output_dir)
        self.dir_edit.setStyleSheet("""
            QLineEdit {
                background-color: #FFFFFF;
                border: 1px solid #CED4DA;
                border-radius: 5px;
                padding: 6px;
                font-size: 13px;
                color: #495057;
            }
            QLineEdit::placeholder {
                color: #6C757D;
            }
        """)
        self.setFont(self.dir_edit, 13)
        dir_layout.addWidget(self.dir_edit, 1)
        
        self.browse_dir_btn = QPushButton("浏览...")
        self.browse_dir_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF"))
        self.browse_dir_btn.setFixedWidth(100)
        self.setFont(self.browse_dir_btn, 12, QFont.Medium)
        self.browse_dir_btn.clicked.connect(self.select_output_dir)
        dir_layout.addWidget(self.browse_dir_btn)
        
        output_layout.addLayout(dir_layout)
        
        # 文件名设置
        filename_layout = QHBoxLayout()
        filename_layout.setSpacing(8)  # 标签-输入框间距8px
        filename_label = QLabel("输出文件名:")
        self.setFont(filename_label, 10)
        filename_label.setStyleSheet("color: #2B2D42; font-weight: bold; min-width: 100px;")  # 确保足够宽度
        filename_layout.addWidget(filename_label)
        
        self.filename_edit = QLineEdit()
        self.filename_edit.setStyleSheet("""
            QLineEdit {
                background-color: #FFFFFF;
                border: 1px solid #CED4DA;
                border-radius: 5px;
                padding: 6px;
                font-size: 13px;
                color: #495057;
            }
            QLineEdit::placeholder {
                color: #6C757D;
            }
        """)
        self.setFont(self.filename_edit, 13)
        filename_layout.addWidget(self.filename_edit, 1)
        
        self.auto_btn = QPushButton("自动生成")
        self.auto_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF"))
        self.auto_btn.setFixedWidth(100)
        self.setFont(self.auto_btn, 12, QFont.Medium)
        self.auto_btn.clicked.connect(self.generate_auto_filename)
        filename_layout.addWidget(self.auto_btn)
        
        output_layout.addLayout(filename_layout)
        
        # 文件类型提示
        type_hint = QLabel("提示：交替合并始终输出PDF格式，直接合并保留原格式\n建议：处理Word文档前先手动转换为PDF，以确保最佳兼容性和稳定性")
        type_hint.setFont(QFont("微软雅黑", 12))
        type_hint.setStyleSheet("font-size: 16px; color: #D90429; font-style: italic; margin-top: 8px;")
        type_hint.setWordWrap(True)
        output_layout.addWidget(type_hint)
        
        self.layout.addWidget(output_box)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #CED4DA;
                border-radius: 8px;
                text-align: center;
                background-color: #FFFFFF;
                height: 25px;
                font-size: 12px;
            }
            QProgressBar::chunk {
                background-color: #4361EE;
                border-radius: 7px;
            }
        """)
        self.setFont(self.progress_bar, 12)
        self.progress_bar.setVisible(False)
        self.layout.addWidget(self.progress_bar)
        
        # 状态显示
        self.status_label = QLabel("就绪")
        self.setFont(self.status_label, 13)
        self.status_label.setStyleSheet("margin-top: 8px; color: #6C757D; font-size: 13px;")
        self.layout.addWidget(self.status_label)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(30, 15, 30, 5)
        
        self.start_btn = QPushButton("开始处理")
        self.start_btn.setStyleSheet(self.get_button_style("#4361EE", "#FFFFFF") + "font-size: 16px;")  # 增大按钮字体
        self.start_btn.setMinimumHeight(40)
        self.start_btn.setFont(QFont("微软雅黑", 22, QFont.Bold))  # 增大按钮字体
        self.start_btn.clicked.connect(self.show_disclaimer)
        
        self.exit_btn = QPushButton("退出")
        self.exit_btn.setStyleSheet(self.get_button_style("#6C757D", "#FFFFFF") + "font-size: 16px;")  # 增大按钮字体
        self.exit_btn.setMinimumHeight(40)
        self.exit_btn.setFont(QFont("微软雅黑", 22))  # 增大按钮字体
        self.exit_btn.clicked.connect(self.close)
        
        button_layout.addWidget(self.start_btn)
        button_layout.addWidget(self.exit_btn)
        
        # 使用 addLayout 方法添加 button_layout 到主布局
        self.layout.addLayout(button_layout)
        
        # 底部版权信息
        footer_label = QLabel("2025 D&Ai 文档合并工具 V2.1.2")
        footer_label.setFont(QFont("微软雅黑", 8))
        footer_label.setStyleSheet("margin-top: 12px; color: #6C757D;")
        footer_label.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(footer_label)
        
        # 连接信号
        self.direct_radio.toggled.connect(self.update_ui_state)
        self.alternating_radio.toggled.connect(self.update_ui_state)
        self.pdf_radio.toggled.connect(self.update_ui_state)
        self.word_radio.toggled.connect(self.update_ui_state)
        self.mixed_radio.toggled.connect(self.update_ui_state)
        self.file1_edit.textChanged.connect(self.file_selected)
        self.file2_edit.textChanged.connect(self.file_selected)
        self.dir_edit.textChanged.connect(self.update_output_path)
        self.filename_edit.textChanged.connect(self.update_output_path)
        
        # 初始UI状态更新
        self.update_ui_state()
    
    def get_app_icon(self):
        """生成应用图标"""
        pixmap = QPixmap(64, 64)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        painter.setBrush(QColor("#4361EE"))
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(12, 8, 40, 48, 8, 8)
        painter.setBrush(QColor("#FFFFFF"))
        painter.drawRect(20, 16, 24, 24)
        painter.setBrush(QColor("#4361EE"))
        painter.drawRect(20, 44, 24, 4)
        painter.end()
        return pixmap
    
    def get_groupbox_style(self):
        """获取组框样式"""
        return f"""
            QGroupBox {{
                border: 1px solid #CED4DA;
                border-radius: 10px;
                margin-top: 1ex;
                padding-top: 15px;
                background-color: #F8F9FA;
            }}
            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top left;
                padding: 0 8px;
                background-color: #F8F9FA;
                color: #2B2D42;
                font-weight: bold;
                font-size: 13px;
                left: 8px;
            }}
        """
    
    def get_button_style(self, bg_color, text_color):
        """获取按钮样式"""
        # 强制使用#3498db作为按钮背景色
        bg_color = "#3498db"
        return f"""
            QPushButton {{
                background-color: {bg_color};
                color: {text_color};
                border: none;
                border-radius: 6px;
                padding: 8px 15px;
                font-weight: bold;
                font-size: 16px;
            }}
            QPushButton:hover {{
                background-color: {self.adjust_color(bg_color, 20)};
            }}
            QPushButton:pressed {{
                background-color: {self.adjust_color(bg_color, -20)};
            }}
        """
    
    def adjust_color(self, color, amount):
        """调整颜色亮度"""
        r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
        r = max(0, min(255, r + amount))
        g = max(0, min(255, g + amount))
        b = max(0, min(255, b + amount))
        return f"#{r:02x}{g:02x}{b:02x}"

    def setFont(self, widget, size=13, weight=QFont.Normal):
        """统一设置字体"""
        font = QFont("微软雅黑", size, weight)
        if not font.exactMatch():
            font.setFamily("Arial")
        widget.setFont(font)

    def get_fallback_font(self):
        """获取系统回退字体"""
        try:
            # 尝试获取系统默认字体
            font = QFont()
            font.setFamily("微软雅黑")
            if not font.exactMatch():
                font.setFamily("Arial")
            if not font.exactMatch():
                font = QFont("sans-serif")
            return font.family()
        except:
            return "Arial, sans-serif"
    
    def paintEvent(self, event):
        """绘制蓝白渐变背景"""
        painter = QPainter(self)
        gradient = QLinearGradient(0, 0, 0, self.height())
        gradient.setColorAt(0.0, QColor(230, 245, 255))  # 顶部颜色 - 浅蓝
        gradient.setColorAt(1.0, QColor(180, 220, 255))  # 底部颜色 - 稍深蓝
        painter.fillRect(self.rect(), gradient)
    
    def update_ui_state(self):
        """根据选择更新UI状态"""
        # 更新逆序选项的可用状态
        alternating_selected = self.alternating_radio.isChecked()
        self.reverse_none.setEnabled(alternating_selected)
        self.reverse_odd.setEnabled(alternating_selected)
        self.reverse_even.setEnabled(alternating_selected)
        self.reverse_both.setEnabled(alternating_selected)
        
        # 自动生成文件名
        self.generate_auto_filename()
    
    def file_selected(self):
        """当文件被选择时更新状态"""
        self.generate_auto_filename()
    
    def generate_auto_filename(self):
        """自动生成文件名"""
        file1 = self.file1_edit.text().strip()
        if not file1:
            return
        
        base_name = os.path.splitext(os.path.basename(file1))[0]
        
        if self.direct_radio.isChecked():
            if self.pdf_radio.isChecked() or self.mixed_radio.isChecked():
                filename = f"{base_name}+合并.pdf"
            else:
                filename = f"{base_name}+合并.docx"
        else:
            filename = f"{base_name}+奇偶合并.pdf"
        
        self.filename_edit.setText(filename)
        self.update_output_path()
    
    def select_output_dir(self):
        """选择输出目录"""
        directory = QFileDialog.getExistingDirectory(
            self, "选择输出目录", self.output_dir
        )
        if directory:
            self.output_dir = directory
            self.dir_edit.setText(directory)
            self.update_output_path()
    
    def select_file(self, file_type):
        """选择文件"""
        if file_type == "file1":
            target_edit = self.file1_edit
            title = "选择第一个文件"
        else:
            target_edit = self.file2_edit
            title = "选择第二个文件"
        
        # 修复文件类型检测问题
        if self.pdf_radio.isChecked():
            file_filter = "PDF文件 (*.pdf)"
        elif self.word_radio.isChecked():
            file_filter = "Word文件 (*.docx *.doc)"
        else:  # mixed
            file_filter = "所有文档 (*.pdf *.docx *.doc)"
            
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            title, 
            self.output_dir, 
            file_filter
        )
        
        if file_path:
            target_edit.setText(file_path)
            self.generate_auto_filename()
    
    def update_output_path(self):
        """更新输出路径"""
        filename = self.filename_edit.text().strip()
        if not filename:
            return
        
        # 确保有正确的文件扩展名
        if self.direct_radio.isChecked():
            if self.pdf_radio.isChecked() or self.mixed_radio.isChecked():
                if not filename.lower().endswith('.pdf'):
                    filename += '.pdf'
            else:
                if not filename.lower().endswith('.docx'):
                    filename += '.docx'
        else:
            if not filename.lower().endswith('.pdf'):
                filename += '.pdf'
        
        self.output_file = os.path.join(self.output_dir, filename)
        self.status_label.setText(f"输出路径: {self.output_file}")
    
    def show_help(self):
        """显示使用说明"""
        help_dialog = QDialog(self)
        help_dialog.setWindowTitle("使用说明")
        help_dialog.setGeometry(100, 100, 700, 550)
        help_dialog.setFont(QFont("微软雅黑", 16))
        
        layout = QVBoxLayout(help_dialog)
        
        # 添加标题
        title_label = QLabel("文档合并工具使用指南")
        title_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #2B2D42;")
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 添加说明文本
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)
        content_layout.setContentsMargins(15, 15, 15, 15)
        
        sections = [
            ("📌 功能概述", "本工具提供两种文档合并方式：<br><br>"
             "1. <b>直接合并</b>：将两个文档首尾相连合并为一个新文档<br>"
             "2. <b>奇偶页交替合并</b>：专为扫描文件设计，将奇数页和偶数页文件交替合并\n\n"
             "支持处理PDF和Word文档，并提供混合模式处理不同类型的文档。"),
            
            ("🚀 操作步骤", 
             "1. <b>选择文档格式</b>：根据您的文档类型选择PDF、Word或混合模式<br>"
             "2. <b>选择合并方式</b>：根据需求选择直接合并或奇偶页交替合并<br>"
             "3. <b>设置逆序选项</b>：如果需要逆序排列文档，选择相应的选项<br>"
             "4. <b>选择文件</b>：点击浏览按钮选择要处理的文件<br>"
             "5. <b>设置输出路径</b>：选择输出目录和文件名<br>"
             "6. <b>开始处理</b>：点击'开始处理'按钮执行合并操作"),
            
            ("📝 文件命名", 
             "• <b>自动生成</b>：点击'自动生成'按钮根据输入文件自动创建文件名<br>"
             "• <b>自定义命名</b>：在文件名输入框中输入您想要的文件名<br>"
             "• <b>文件扩展名</b>：工具会根据文档类型自动添加正确的扩展名"),
            
            ("⚠️ 重要提示", 
             "• <b><b>免责声明</b>：本软件为免费工具，用户自愿使用。开发者不承诺软件绝对安全，对因使用软件导致的数据丢失、系统损坏等后果不承担责任。禁止将软件用于非法目的。<br>"
             "• <b>奇偶页交替合并始终输出PDF格式</b><br>"
             "• <b>直接合并会保留原始文档格式</b><br>"
             "• <b>混合模式可以同时处理PDF和Word文档</b><br>"
             "• <b>大文件处理可能需要较长时间，请耐心等待</b><br>"
             "• <b>逆序处理会产生以'_n'结尾的临时文件，用户可手动删除</b><br>"
             "• <b>强烈建议</b>：处理Word文档前先手动转换为PDF格式，以确保最佳兼容性和稳定性"),

            ("📜 版本更新历史",
             "<b>版本 2.1.2 (2025年7月18日)</b><br>"
             "1. UI优化<br>"
             "   - 优化了按钮及显示效果<br><br>"
             
             "<b>版本 2.1.1 (2025年7月10日)</b><br>"
             "1. 免责声明<br>"
             "   - 新增软件免责声明，明确责任边界<br>"
             "2. UI优化<br>"
             "   - 与FileGatherPro统一，采用蓝白渐变主题背景<br>"
             "   - 调整按钮和文本控件样式<br><br>"
             
             "<b>版本 2.1.0 (2025年7月4日)</b><br>"
             "1. 安全声明<br>"
             "   - 首次运行时显示安全警告说明<br>"
             "2. 日志系统<br>"
             "   - 添加操作日志记录功能<br>"
             "3. 临时文件管理<br>"
             "   - 程序关闭时自动清理临时文件<br>"
             "4. COM接口优化<br>"
             "   - 使用pythoncom安全初始化COM<br><br>"
             
             "<b>版本 2.0.2 (2025年7月2日)</b><br>"
             "1. 混合模式支持<br>"
             "   - 新增PDF+Word混合文档处理<br>"
             "2. 帮助系统<br>"
             "   - 集成详细使用说明对话框<br>"
             "3. 文件名管理<br>"
             "   - 添加'自动生成文件名'功能<br>"
             "4. 进度显示优化<br>"
             "   - 改进进度条实时反馈机制<br>"
             "5. 错误处理<br>"
             "   - 增强异常捕获和用户提示<br><br>"
             
             "<b>版本 2.0 (2025年7月1日)</b><br>"
             "1. 全新UI设计<br>"
             "   - 采用分组布局和渐变背景<br>"
             "2. 逆序选项扩展<br>"
             "   - 支持四种逆序模式<br>"
             "3. 输出设置<br>"
             "   - 增加输出目录选择功能<br>"
             "4. 进度指示<br>"
             "   - 添加进度条显示处理状态<br>"
             "5. 文件预览<br>"
             "   - 实时显示输出文件路径<br><br>"
             
             "<b>版本 1.0 (2025年7月1日)</b><br>"
             "1. 基础功能实现<br>"
             "   - 支持PDF/Word直接合并<br>"
             "   - 支持奇偶页交替合并<br>"
             "2. 逆序处理<br>"
             "   - 添加文档逆序排列功能<br>"
             "3. 格式转换<br>"
             "   - 集成Word转PDF功能<br>"
             "4. UI框架<br>"
             "   - 建立基本操作界面布局<br><br>"
             
             "<b>初始版本0.0 （纯代码运行）(2025年7月1日)</b><br>"
             "1. 核心功能<br>"
             "   - PDF奇偶页合并基础实现<br>"
             "2. 空白页处理<br>"
             "   - 自动补充缺失的空白页<br>"
             "3. 命令行交互<br>"
             "   - 通过终端输入文件路径<br>"
             "4. 错误检查<br>"
             "   - 基础文件存在性验证"),
            
            
        ]
        
        for title, content in sections:
            section_title = QLabel(title)
            section_title.setStyleSheet("font-size: 15px; font-weight: bold; color: #4361EE; margin-top: 12px;")
            content_layout.addWidget(section_title)
            
            section_content = QLabel(content)
            section_content.setStyleSheet("font-size: 17px; color: #2B2D42; margin-bottom: 12px; margin-left: 8px;")
            section_content.setWordWrap(True)
            section_content.setOpenExternalLinks(True)
            content_layout.addWidget(section_content)
        
        content_layout.addStretch()
        scroll_area.setWidget(content_widget)
        layout.addWidget(scroll_area)
        
        # 添加关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.setStyleSheet(self.get_button_style("#4361EE", "#FFFFFF") + "font-size: 14px;")
        close_btn.setFont(QFont("微软雅黑", 14))
        close_btn.clicked.connect(help_dialog.accept)
        layout.addWidget(close_btn)
        
        help_dialog.exec_()
    
    def check_first_run(self):
        """检查是否是首次运行并显示法律声明"""
        config_path = os.path.join(os.path.expanduser("~"), ".pdf_word_merger_config")
        if not os.path.exists(config_path):
            self.show_legal_notice()
            with open(config_path, "w") as f:
                f.write("1")  # 标记已显示过声明
    
    def show_legal_notice(self):
        """显示法律声明"""
        disclaimer = """
        【法律声明】
        1. 本工具仅提供文档格式转换和合并功能
        2. 用户需确保对处理文档拥有合法权限
        3. 禁止用于破解加密文档或侵犯版权
        4. Microsoft Word 功能需用户自行授权
        """
        QMessageBox.information(self, "法律声明", disclaimer.strip())
    
    def show_disclaimer(self):
        """显示操作免责声明对话框"""
        disclaimer = QMessageBox()
        disclaimer.setWindowTitle("免责声明")
        disclaimer.setIcon(QMessageBox.Warning)
        disclaimer.setText("""
        <b>免责声明</b>
        <p>本软件为免费工具，用户自愿使用。开发者不承诺软件绝对安全，对因使用软件导致的数据丢失、系统损坏等后果不承担责任。</p>
        <p>禁止将软件用于非法目的。</p>
        """)
        disclaimer.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        disclaimer.setDefaultButton(QMessageBox.Ok)
        disclaimer.button(QMessageBox.Ok).setText("同意并继续")
        disclaimer.button(QMessageBox.Cancel).setText("取消")
        
        result = disclaimer.exec_()
        if result == QMessageBox.Ok:
            self.start_processing()
    
    def start_processing(self):
        """开始处理流程"""
        # 获取用户选择
        if self.pdf_radio.isChecked():
            self.file_type = "pdf"
        elif self.word_radio.isChecked():
            self.file_type = "word"
        else:
            self.file_type = "mixed"
            
        self.merge_type = "direct" if self.direct_radio.isChecked() else "alternating"
        
        # 获取逆序选项
        if self.reverse_none.isChecked():
            self.reverse_option = "none"
        elif self.reverse_odd.isChecked():
            self.reverse_option = "odd"
        elif self.reverse_even.isChecked():
            self.reverse_option = "even"
        else:
            self.reverse_option = "both"
        
        # 获取输出目录
        self.output_dir = self.dir_edit.text().strip()
        if not self.output_dir:
            QMessageBox.warning(self, "警告", "请选择输出目录！")
            return
            
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
        
        # 获取文件名
        filename = self.filename_edit.text().strip()
        if not filename:
            QMessageBox.warning(self, "警告", "请输入输出文件名！")
            return
        
        self.update_output_path()
        
        # 获取文件路径
        self.first_file = self.file1_edit.text().strip()
        if not self.first_file:
            QMessageBox.warning(self, "警告", "请选择第一个文件！")
            return
            
        self.second_file = self.file2_edit.text().strip()
        if not self.second_file:
            QMessageBox.warning(self, "警告", "请选择第二个文件！")
            return
        
        try:
            # 重置进度条
            self.progress_bar.setRange(0, 100)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            
            # 直接合并
            if self.merge_type == "direct":
                self.direct_merge()
            # 奇偶页交替合并
            else:
                # 处理逆序
                if self.reverse_option in ["odd", "both"]:
                    self.status_label.setText("正在逆序奇数页文件...")
                    self.progress_bar.setValue(10)
                    QApplication.processEvents()
                    self.first_file = self.reverse_document(self.first_file)
                
                if self.reverse_option in ["even", "both"]:
                    self.status_label.setText("正在逆序偶数页文件...")
                    self.progress_bar.setValue(30)
                    QApplication.processEvents()
                    self.second_file = self.reverse_document(self.second_file)
                
                # 进行合并
                self.status_label.setText("正在合并文档...")
                self.progress_bar.setValue(50)
                QApplication.processEvents()
                self.alternating_merge()
                
            # 完成处理
            self.progress_bar.setValue(100)
            self.status_label.setText("操作完成！")
            
            # 创建自定义消息框
            msg_box = QMessageBox()
            msg_box.setWindowTitle("操作成功")
            msg_box.setIcon(QMessageBox.Information)
            msg_box.setText(f"文档合并完成！\n输出文件: {self.output_file}")
            
            # 添加打开文档按钮
            open_btn = msg_box.addButton("打开文档", QMessageBox.ActionRole)
            open_btn.clicked.connect(lambda: os.startfile(self.output_file))
            
            # 添加确定按钮
            msg_box.addButton(QMessageBox.Ok)
            
            # 显示消息框
            msg_box.exec_()
            
            # 重置UI
            self.progress_bar.setVisible(False)
            self.status_label.setText("就绪")
            
        except Exception as e:
            self.progress_bar.setVisible(False)
            QMessageBox.critical(self, "错误", f"处理过程中发生错误: {str(e)}")
            self.status_label.setText(f"错误: {str(e)}")

    def reverse_document(self, file_path):
        """逆序排列文档并保存"""
        try:
            # 获取输出路径
            base_name = os.path.splitext(os.path.basename(file_path))[0]
            ext = os.path.splitext(file_path)[1].lower()
            output_path = os.path.join(self.output_dir, f"{base_name}_n{ext}")
            
            # PDF逆序
            if ext == '.pdf':
                reader = PdfReader(file_path)
                writer = PdfWriter()
                
                # 逆序添加页面
                for i in range(len(reader.pages)-1, -1, -1):
                    writer.add_page(reader.pages[i])
                
                # 保存逆序后的PDF
                with open(output_path, "wb") as out_file:
                    writer.write(out_file)
            
            # Word逆序
            else:
                doc = Document(file_path)
                new_doc = Document()
                
                # 复制样式
                for section in doc.sections:
                    new_section = new_doc.add_section(section.start_type)
                    new_section.page_width = section.page_width
                    new_section.page_height = section.page_height
                    new_section.left_margin = section.left_margin
                    new_section.right_margin = section.right_margin
                    new_section.top_margin = section.top_margin
                    new_section.bottom_margin = section.bottom_margin
                    new_section.header_distance = section.header_distance
                    new_section.footer_distance = section.footer_distance
                
                # 逆序添加段落
                for i in range(len(doc.paragraphs)-1, -1, -1):
                    new_doc.add_paragraph(doc.paragraphs[i].text)
                
                # 保存逆序后的Word文档
                new_doc.save(output_path)
            
            return output_path
        
        except Exception as e:
            raise Exception(f"逆序处理失败: {str(e)}")

    def direct_merge(self):
        """直接合并两个文档"""
        self.status_label.setText("正在合并文档...")
        self.progress_bar.setValue(30)
        QApplication.processEvents()
        
        # 获取文件扩展名
        ext1 = os.path.splitext(self.first_file)[1].lower()
        ext2 = os.path.splitext(self.second_file)[1].lower()
        
        # 处理混合模式
        if self.file_type == "mixed":
            # 转换Word为PDF
            if ext1 in ['.doc', '.docx']:
                temp_pdf1 = os.path.join(tempfile.gettempdir(), "temp1.pdf")
                self.convert_word_to_pdf(self.first_file, temp_pdf1)
                self.first_file = temp_pdf1
            
            if ext2 in ['.doc', '.docx']:
                temp_pdf2 = os.path.join(tempfile.gettempdir(), "temp2.pdf")
                self.convert_word_to_pdf(self.second_file, temp_pdf2)
                self.second_file = temp_pdf2
            
            # 合并PDF
            self.merge_pdf_files(self.first_file, self.second_file)
        else:
            # PDF直接合并
            if ext1 == '.pdf' and ext2 == '.pdf':
                self.merge_pdf_files(self.first_file, self.second_file)
            # Word直接合并
            else:
                # 创建新文档
                merged_doc = Document()
                
                # 添加第一个文档内容
                doc1 = Document(self.first_file)
                for element in doc1.element.body:
                    merged_doc.element.body.append(element)
                
                # 添加第二个文档内容
                doc2 = Document(self.second_file)
                for element in doc2.element.body:
                    merged_doc.element.body.append(element)
                
                # 保存合并后的Word文档
                merged_doc.save(self.output_file)
        
        self.progress_bar.setValue(100)
    
    def merge_pdf_files(self, file1, file2):
        """合并两个PDF文件"""
        merger = PdfWriter()
        
        # 添加第一个文件
        with open(file1, "rb") as f1:
            merger.append(f1)
        
        # 添加第二个文件
        with open(file2, "rb") as f2:
            merger.append(f2)
        
        # 保存合并后的PDF
        with open(self.output_file, "wb") as out_file:
            merger.write(out_file)

    def alternating_merge(self):
        """奇偶页交替合并"""
        # 确保输出为PDF
        if not self.output_file.lower().endswith('.pdf'):
            self.output_file += '.pdf'
        
        # 处理混合模式
        if self.file_type == "mixed":
            # 转换Word为PDF
            if self.first_file.lower().endswith(('.doc', '.docx')):
                temp_pdf1 = os.path.join(tempfile.gettempdir(), "temp1.pdf")
                self.convert_word_to_pdf(self.first_file, temp_pdf1)
                self.first_file = temp_pdf1
            
            if self.second_file.lower().endswith(('.doc', '.docx')):
                temp_pdf2 = os.path.join(tempfile.gettempdir(), "temp2.pdf")
                self.convert_word_to_pdf(self.second_file, temp_pdf2)
                self.second_file = temp_pdf2
        
        # 进行合并
        self.alternating_merge_pdf(self.first_file, self.second_file)
    
    def alternating_merge_pdf(self, odd_path, even_path):
        """PDF奇偶页交替合并"""
        self.status_label.setText("正在交替合并页面...")
        self.progress_bar.setValue(60)
        QApplication.processEvents()
        
        # 读取PDF文件
        odd_reader = PdfReader(odd_path)
        even_reader = PdfReader(even_path)
        
        # 创建PDF写入器
        writer = PdfWriter()
        
        # 获取页数
        odd_count = len(odd_reader.pages)
        even_count = len(even_reader.pages)
        total_pages = max(odd_count, even_count)
        
        # 设置进度条范围
        self.progress_bar.setRange(0, total_pages)
        
        # 交替合并页面
        for i in range(total_pages):
            # 更新进度
            progress = 60 + int(40 * (i / total_pages))
            self.progress_bar.setValue(progress)
            self.status_label.setText(f"正在处理第 {i+1}/{total_pages} 页...")
            QApplication.processEvents()
            
            # 添加奇数页（如果存在）
            if i < odd_count:
                writer.add_page(odd_reader.pages[i])
            
            # 添加偶数页（如果存在）
            if i < even_count:
                writer.add_page(even_reader.pages[i])
        
        # 保存合并后的PDF
        with open(self.output_file, "wb") as out_file:
            writer.write(out_file)
        
        self.progress_bar.setValue(100)

    def convert_word_to_pdf(self, word_path, pdf_path):
        """将Word文档转换为PDF"""
        try:
            self.status_label.setText(f"正在转换 {os.path.basename(word_path)} 为PDF...")
            QApplication.processEvents()
            
            # 使用COM接口转换Word为PDF
            word = comtypes.client.CreateObject("Word.Application")
            word.Visible = False
            
            # 处理绝对路径
            abs_word_path = os.path.abspath(word_path)
            abs_pdf_path = os.path.abspath(pdf_path)
            
            doc = word.Documents.Open(abs_word_path)
            doc.SaveAs(abs_pdf_path, FileFormat=17)  # 17 = PDF format
            doc.Close()
            word.Quit()
            
            # 确保文件已创建
            if not os.path.exists(abs_pdf_path):
                raise Exception("Word转PDF失败：文件未创建")
                
        except Exception as e:
            # 添加更详细的错误信息
            error_msg = f"Word转PDF失败: {str(e)}"
            if "Quit" in str(e):
                error_msg += "\n提示：此错误通常不影响转换结果，请检查输出文件是否已生成"
            raise Exception(error_msg)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用样式
    app.setStyle("Fusion")
    
    # 设置全局字体
    app.setFont(QFont("微软雅黑", 10))
    
    # 设置全局调色板 - 蓝白主题
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(230, 245, 255))  # 窗口背景色
    palette.setColor(QPalette.WindowText, QColor("#2B2D42"))  # 窗口文本色
    palette.setColor(QPalette.Base, QColor("#FFFFFF"))        # 输入组件背景色
    palette.setColor(QPalette.AlternateBase, QColor(220, 240, 255)) # 交替行背景色
    palette.setColor(QPalette.ToolTipBase, QColor("#2B2D42")) # 工具提示背景色
    palette.setColor(QPalette.ToolTipText, QColor("#FFFFFF")) # 工具提示文本色
    palette.setColor(QPalette.Text, QColor("#2B2D42"))        # 文本颜色
    palette.setColor(QPalette.Button, QColor(200, 230, 255))  # 按钮背景色
    palette.setColor(QPalette.ButtonText, QColor("#2B2D42"))  # 按钮文本色
    palette.setColor(QPalette.BrightText, QColor("#4361EE"))  # 高亮文本色
    palette.setColor(QPalette.Highlight, QColor("#4361EE"))   # 选中项高亮色
    palette.setColor(QPalette.HighlightedText, QColor("#FFFFFF")) # 选中项文本色
    app.setPalette(palette)
    
    window = FileMergerApp()
    window.show()
    sys.exit(app.exec_())
